import cv2
import numpy as np


def show(img):
    cv2.imshow('Detected Dots', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# 读取图像
image = cv2.imread(r"E:\Blender\left_camera.png", cv2.IMREAD_GRAYSCALE)


# 二值化处理
_, binary_image = cv2.threshold(image, 25, 255, cv2.THRESH_BINARY_INV)

# 形态学操作
kernel = np.ones((3, 3), np.uint8)
binary_image = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel)

# 连通域分析
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image, connectivity=8)

labels = labels.astype(np.uint8)

suit_label = []

# 绘制检测到的黑色点
for i in range(1, num_labels):
    x, y, w, h, area = stats[i]
    if area < 3000:  # 过滤掉小区域
        suit_label.append(i)


mask = np.isin(labels, suit_label)
labels[mask] = 255
labels[~mask] = 0

# 显示结果
cv2.imshow('Detected Dots', labels)
cv2.waitKey(0)
cv2.destroyAllWindows()
